package com.srkj.controller;

import com.srkj.entity.Sys_user;
import com.srkj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * com.srkj.repository
 * Created by zhangshaoxiong
 * data : 2018 11:21
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 查询所有
     * @return
     */
    @GetMapping("/users")
    public String findAllUser(Model model) throws Exception{
        List<Sys_user> allUser = userService.findAllUser();
        model.addAttribute("users",allUser);
        return "user/list";
    }
    /**
     * 查询所有
     * @return
     */
    @GetMapping("/user")
    public String addUser(Model model) throws Exception{
        return "user/add";
    }

    /**
     * 新增user
     * @return
     */
    @PostMapping("/user")
    public String tosaveUser(Sys_user user) throws Exception{
        if (user != null){
            userService.saveUser(user);
        }
        return "redirect:/users";
    }
    /**
     * 修改user
     * @return
     */
    @GetMapping("/user/{user_id}")
    public String toeditUser(@PathVariable("user_id") Integer user_id,Model model) throws Exception{

        Sys_user byUserId = userService.findByUserId(user_id.longValue());
        model.addAttribute("user",byUserId);
        return "user/add";
    }

    /**
     * 修改user
     * @return
     */
    @PutMapping("/user")
    public String updateUser(Sys_user user) throws Exception{

        Sys_user dbUser = userService.findByUserId(user.getUser_id());
        if (dbUser!= null){
            userService.updateUser(user);
        }
        return "redirect:/users";
    }


    /**
     * 删除user
     * @return
     */
    @DeleteMapping("/user/{user_id}")
    public String deleteUser(@PathVariable("user_id") Integer user_id) throws Exception{

        Sys_user dbUser = userService.findByUserId(user_id);
        if (dbUser!= null){
            userService.deleteUser(dbUser.getUser_id());
        }
        return "redirect:/users";
    }
}
